package model

import (
	"context"

	"github.com/LyricTian/gin-admin/v7/internal/app/contextx"
	"github.com/LyricTian/gin-admin/v7/internal/app/model/gormx/entity"
	"github.com/LyricTian/gin-admin/v7/internal/app/schema"
	"github.com/LyricTian/gin-admin/v7/pkg/errors"
	"github.com/jinzhu/gorm"
)

//设置用户id,用户不存在时，会自动创建
func (a *UserInfo) SetPid(ctx context.Context, pid string) error {
	uid, ok := contextx.FromUserID(ctx)
	if !ok {
		return errors.New400Response("用户不存在")
	}
	if len(uid) == 0 {
		return errors.New400Response("用户不存在")
	}

	item, err := a.Get(ctx, uid)
	if err != nil {
		return err
	}

	if item == nil {
		return a.CreateUserInfo(ctx, pid)
	}

	return a.Update(ctx, uid, schema.UserInfo{Pid: pid})
}

func (a *UserInfo) CreateUserInfo(ctx context.Context, pid string) error {
	uid, ok := contextx.FromUserID(ctx)
	if !ok {
		return errors.New400Response("用户不存在")
	}
	if len(uid) == 0 {
		return errors.New400Response("用户不存在")
	}

	item, err := a.Get(ctx, uid)
	if err != nil {
		return err
	}

	if item == nil {
		userModel := User{DB: a.DB}
		user, err := userModel.Get(ctx, uid)
		if err != nil {
			return err
		}

		return a.Create(ctx, schema.UserInfo{ID: user.ID, Username: user.UserName, RealName: user.RealName, Phone: user.Phone, Pid: pid, Status: 1, AccountNum: user.ID, IsNewer: 1})
	}
	return nil
}

//设置用户pid
func (a *UserInfo) SetPidByAccountNum(ctx context.Context, accountNum string) error {
	item, err := a.GetFirst(ctx, schema.UserInfoQueryParam{AccountNum: accountNum})
	if err != nil {
		return err
	}
	if item == nil {
		return errors.New400Response("邀请码不存在")
	}
	return a.SetPid(ctx, item.Pid)
}

//通过邀请码获取用户
func (a *UserInfo) GetPidByAccountNum(ctx context.Context, accountNum string) *schema.UserInfo {
	item, _ := a.GetFirst(ctx, schema.UserInfoQueryParam{AccountNum: accountNum})
	return item
}

// todo 添加一天
func (a *UserInfo) AddReciteDay(ctx context.Context) {
	db := entity.GetGroupMemberDB(ctx, a.DB)
	db.Update("all_recite_day", gorm.Expr("recite_day + ?", 1))
	//GetSqlX(a.DB).Exec("update g_group_member set recite_day=recite_day+1 ")
}
